package com.qf.service.impl;

import com.qf.service.AggSearchService;
import com.qf.util.ElasticsearchUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.range.Range;
import org.elasticsearch.search.aggregations.bucket.range.RangeAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;
import java.util.List;

public class AggSearchServiceImpl implements AggSearchService {

    private RestHighLevelClient client = ElasticsearchUtil.client();

    @Override
    public void rangeQuery(String index, String type) throws IOException {
        //1. 创建request
        SearchRequest request = new SearchRequest();

        //2. 封装request
        //2.1 设置索引和类型
        request.indices(index);
        request.types(type);

        //2.2 创建SearchSourceBuilder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //2.3 设置Agg聚合查询 - range数值范围
        RangeAggregationBuilder rangeAgg = AggregationBuilders
                .range("agg")
                .field("fee")
                .addUnboundedTo(5)
                .addRange(5, 7)
                .addUnboundedFrom(7);
        sourceBuilder.aggregation(rangeAgg);

        //2.4 SearchSourceBuilder设置到request
        request.source(sourceBuilder);

        //3. 执行查询
        SearchResponse resp = client.search(request, RequestOptions.DEFAULT);

        //4. 从resp中获取数据
        Range agg = resp.getAggregations().get("agg");
        for (Range.Bucket bucket : agg.getBuckets()) {
            Object key = bucket.getKey();
            long docCount = bucket.getDocCount();
            System.out.println("查询出范围在" + key + "内,有" + docCount + "条数据!!!");
        }


    }
}
